package com.kth.subtranslator;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

public class SrtParser {

	public List<SrtEntry> parse(final String fileName) {
		List<SrtEntry> entries = new ArrayList<SrtEntry>();
		FileInputStream fis;
		try {
			fis = new FileInputStream(fileName);
			LineNumberReader r = new LineNumberReader( new InputStreamReader(fis) );
			String numberString;
			while ((numberString = r.readLine()) != null) {
	            String timeString = r.readLine();
	            String lineString = "";
	            String s;
	            while (!((s = r.readLine()) == null || s.trim().equals(""))) {
	                lineString += s + "\n";
	            }

	            String startTime = timeString.split("-->")[0];
	            String endTime = timeString.split("-->")[1];
	            
	            SrtEntry entry = new SrtEntry(Integer.parseInt(numberString), startTime, endTime, lineString);
	            entries.add(entry);
			}
			r.close();
			
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		catch (RuntimeException e) {
			throw new RuntimeException("Subtitle file is not supported");
		}
		
		return entries;
	}
	
	public String parse(List<SrtEntry> entries) {
		StringBuilder sb = new StringBuilder();
		for (SrtEntry srtEntry : entries) {
			sb.append(srtEntry.getId()).append("\n");
			sb.append(srtEntry.getStartTime()).append(" --> ").append(srtEntry.getEndTime()).append("\n");
			sb.append(srtEntry.getContent()).append("\n");
			sb.append("\n");
		}
		return sb.toString();
	}
	
}
